﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.ProductionPlans;
using Reporting.Domain;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.ProductionPlans;
using Reporting.Infrastructure.Interfaces.Sourcetypes;

namespace Reporting.API.Application.CommandHandler.ProductionPlans
{
    public class ReverseProductionPlanCommandHandler : IRequestHandler<ReverseProductionPlanCommand, ApiResult<ProductionPlan>>
    {
        private readonly IProductionPlanRepository _productionPlanRepository;
        private readonly ISourcetypeRepository _sourcetypeRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<ReverseProductionPlanCommandHandler> _logger;

        public ReverseProductionPlanCommandHandler(ILogger<ReverseProductionPlanCommandHandler> logger, IMapper mapper, IProductionPlanRepository productionPlanRepository, ISourcetypeRepository sourcetypeRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _productionPlanRepository = productionPlanRepository;
            _sourcetypeRepository = sourcetypeRepository;
        }


        public async Task<ApiResult<ProductionPlan>> Handle(ReverseProductionPlanCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有生产计划
                var ProductionPlans = await _productionPlanRepository.GetAsync(x => x.Productionplanid == request.Productionplanid);

                // 使用 AutoMapper 进行对象映射
                var productionorderPlanResponses = _mapper.Map<ProductionPlan>(ProductionPlans);


                // 返回成功结果
                return ApiResult<ProductionPlan>.Success(productionorderPlanResponses, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询失败");

                // 返回失败结果
                return ApiResult<ProductionPlan>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }



    }
}
